# -*- coding: UTF-8 -*-
"""
@项目名称：rmq_utiltools.py
@作   者：陆地起飞全靠浪
@创建日期：2025-09-19-15:09
"""
import pika  # pika==1.3.2
from rabbit_mq.rmq_config import cfg, logger


def get_rmq_connection():
    # 连接到RabbitMQ服务器
    # params = pika.ConnectionParameters('localhost')
    credentials = pika.PlainCredentials(username=cfg['rbq_username'], password=cfg['rbq_password'])
    # heatbeat参数，生产者在一定时间内和服务端没有数据来往，服务端会自动断开连接，不会一直保持connection状态。heatbeat=0不发送心跳，服务端永远不会断开这个连接；
    params = pika.ConnectionParameters(host=cfg['rbq_host'], port=cfg['rbq_port'], virtual_host='/aidd_vhost', credentials=credentials, heartbeat=0)
    connection = pika.BlockingConnection(params)
    channel = connection.channel()
    return connection, channel


def rmq_sent(json_dumps='{"xx": 6, "yy": "对对对"}', queue_name='phore_gen'):
    # 发送消息,要发送消息，首先需要建立与RabbitMQ服务器的连接，然后创建一个队列，并通过交换器发送消息。以下是一个简单的生产者示例：
    connection, channel = get_rmq_connection()
    # 声明队列
    channel.queue_declare(queue=queue_name, durable=True)  # durable重启后队列仍然存在
    # 发送消息
    properties = pika.BasicProperties(delivery_mode=2)  # delivery_mode=2 (设置 1为不持久化 ; 设置 2为持久化,重启后消息仍然存在)
    channel.basic_publish(exchange='', routing_key=queue_name, body=json_dumps, properties=properties)
    logger.info(f" [x] Sent '{json_dumps}'")
    # 关闭连接
    connection.close()
